<template>
	<el-drawer
	  v-model="dialog.visible"
	  :title="dialog.title"
	  append-to-body
	  @close="closeDialog"
	  size="750"
	  :close-on-click-modal="false"
	>
	
	  <el-scrollbar >

		<el-form
			ref="formRef"
			:model="formData"
			:rules="formRules"
			label-width="120px"
		>
			
			<div style="margin-bottom: 18px;">
				<span class="title-form_primary">基础信息</span>
			</div>
			
			<el-form-item label="客户端名称" prop="name">
				<el-input v-model="formData.name" placeholder="请输入客户端名称" />
			</el-form-item>
			
			<el-form-item label="标识前缀" prop="prefix">
				<el-input v-model="formData.prefix" placeholder="请输入标识前缀，例如：mqtt_1213" />
			</el-form-item>
			
			<el-form-item label="服务器地址" prop="host">
				<el-input v-model="formData.host" placeholder="请输入MQTT服务器地址，例如：tcp://localhost:1883" />
			</el-form-item>
			
			<el-form-item label="账号" prop="username">
				<el-input v-model="formData.username" placeholder="请输入账号" />
			</el-form-item>
			
			<el-form-item label="密码" prop="password">
				<el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password />
			</el-form-item>
			
			<el-form-item label="超时时间" prop="timeout">
				<el-input-number 
					v-model="formData.timeout" 
					:min="1"
					:max="60"
					placeholder="超时时间"
				>
					<template #append>秒</template>
				</el-input-number>
			</el-form-item>
			
			<el-form-item label="心跳间隔" prop="keepalive">
				<el-input-number 
					v-model="formData.keepalive" 
					:min="10"
					:max="120"
					placeholder="心跳检测间隔"
				>
					<template #append>秒</template>
				</el-input-number>
			</el-form-item>
			
			<el-form-item label="是否启用" prop="enabled" >
				<el-radio-group v-model="formData.enabled" >
				  <el-radio :value="'0'">禁用</el-radio>
				  <el-radio :value="'1'">启用</el-radio>
				</el-radio-group>
			</el-form-item>
			
			<el-form-item label="默认执行" prop="defaultRunning" >
				<el-radio-group v-model="formData.defaultRunning" >
				  <el-radio :value="'0'">手动</el-radio>
				  <el-radio :value="'1'">自动</el-radio>
				</el-radio-group>
			</el-form-item>
			
			<el-form-item label="默认执行" prop="use" >
				<el-radio-group v-model="formData.use" >
				  <el-radio :value="'0'">系统</el-radio>
				  <el-radio :value="'1'">业务</el-radio>
				</el-radio-group>
			</el-form-item>
			
			<el-form-item label="客户端类型" prop="type">
				<el-radio-group v-model="formData.type">
					<el-radio-button value="0">消费者</el-radio-button>
					<el-radio-button value="1">生产者</el-radio-button>
					<el-radio-button value="2">消费者&生产者</el-radio-button>
				</el-radio-group>
			</el-form-item>
			
			<!-- 订阅主题部分 - 只在消费者和消费者&生产者模式下显示 -->
			<template v-if="formData.type === '0' || formData.type === '2'">
				<div style="margin: 18px 0;">
					<span class="title-form_primary">订阅主题</span>
				</div>
				
				<div class="subscription-content">
					<el-table :data="formData.topics" border style="width: 100%">
						<el-table-column prop="name" label="主题" min-width="120" />
						<el-table-column prop="qos" label="QoS" width="80" align="center" />
						<el-table-column label="操作" width="200" fixed="right">
							<template #default="{ $index, row }">
								<el-button link type="primary" @click="editTopic($index)">编辑</el-button>
								<el-button link type="primary" @click="processTopic($index, row)">流程</el-button>
								<el-button link type="danger" @click="removeTopic($index)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>

					<div style="margin-top: 10px;">
						<el-button type="primary" @click="addTopic">添加主题</el-button>
					</div>
				</div>
			</template>

			<!-- 发布主题部分 - 只在生产者和消费者&生产者模式下显示 -->
			<template v-if="formData.type === '1' || formData.type === '2'">
				<div style="margin: 18px 0;">
					<span class="title-form_primary">发布主题</span>
				</div>

				<div class="publish-content">
					<el-table :data="formData.publishTopics" border style="width: 100%">
						<el-table-column prop="name" label="名称" min-width="120" />
						<el-table-column prop="topic" label="发布主题" min-width="180" show-overflow-tooltip />
						<el-table-column prop="qos" label="QoS" width="80" align="center" />
						<el-table-column label="操作" width="150" fixed="right">
							<template #default="{ $index }">
								<el-button link type="primary" @click="editPublish($index)">编辑</el-button>
								<el-button link type="danger" @click="removePublish($index)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>

					<div style="margin-top: 10px;">
						<el-button type="primary" @click="addPublish">添加主题</el-button>
					</div>
				</div>
			</template>
		</el-form>
		
		</el-scrollbar>
	
		<template #footer>
		  <div class="dialog-footer">
			<el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
			<el-button @click="closeDialog">取 消</el-button>
		  </div>
		</template>
	</el-drawer>

	<!-- 主题编辑弹窗 -->
	<EditTopicDialog
		v-model="showTopicDialog"
		:edit-index="editingTopicIndex"
		:edit-data="editingTopicData"
		:topics="formData.topics"
		@confirm="handleTopicConfirm"
	/>

	<!-- 发布主题编辑弹窗 -->
	<EditPublishDialog
		v-model="showPublishDialog"
		:edit-index="editingPublishIndex"
		:edit-data="editingPublishData"
		:publish-topics="formData.publishTopics"
		@confirm="handlePublishConfirm"
	/>
	
	<MqttDataProcessDrawer
		ref="dataProcessDrawerRef"
		@confirm="handleTopicConfirm"
	/>
	
</template>

<script lang="ts" setup>
	
	import MqttAPI from "@/api/biz/LDMPMqttClient";
	import type {FormRules } from 'element-plus'
	import EditTopicDialog from './EditTopicDialog.vue'
	import EditPublishDialog from './EditPublishDialog.vue'
	
	import MqttDataProcessDrawer from "@/components/DataWorkflow/MqttDataProcessDrawer.vue";

	// 1. 基础响应式变量
	const loading = ref(false);
	const dialog = ref({
		visible: false,
		title: '',
	});
	
	const dataProcessDrawerRef=ref();
	
	const formRef = ref();

	// 2. 常量定义
	const DEFAULT_TIMEOUT = 5000;

	// 表单验证规则
	const formRules = reactive<FormRules>({
		name: [{ required: true, message: "客户端名称不能为空", trigger: "blur" }],
		prefix: [{ required: true, message: "客户端标识前缀不能为空", trigger: "blur" }],
		host: [{ required: true, message: "服务器地址不能为空", trigger: "blur" }],
		username: [{ required: true, message: "账号不能为空", trigger: "blur" }],
		password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
		timeout: [
			{ required: true, message: "超时时间不能为空", trigger: "blur" },
			{ type: 'number', min: 1, max: 60, message: '超时时间范围 1-60 秒', trigger: 'blur' }
		],
		keepalive: [
			{ required: true, message: "心跳间隔不能为空", trigger: "blur" },
			{ type: 'number', min: 10, max: 120, message: '心跳间隔范围 10-120 秒', trigger: 'blur' }
		],
		type: [{ required: true, message: "客户端类型不能为空", trigger: "change" }]
	});

	// 定义表单数据接口
	interface FormData {
		id?: string;
		name?: string;
		prefix: string;
		host: string;
		username: string;
		password: string;
		timeout: number;
		keepalive: number;
		type: '0' | '1' | '2';  // 0: 消费者, 1: 生产者, 2: 消费者&生产者
		topics: Topic[];
		publishTopics: Topic[];
		enabled:'0' | '1';
		defaultRunning:'0' | '1';
		use:'0' | '1'
	}

	// Topic 类型定义
	interface Topic {
		name: string;      // 名称
		prefix: string;     // 主题前缀
		topic: string;      // 订阅主题
		qos: '0' | '1' | '2';  // QoS等级
		remark: string;      // 备注
	}

	// 4. 表单数据
	const formData = ref<FormData>({
		prefix: '',
		host: '',
		username: '',
		password: '',
		timeout: DEFAULT_TIMEOUT,
		keepalive: 60,
		type: '0',
		topics: [],
		publishTopics: [],
		enabled:'0',
		defaultRunning:'0',
		use:'0'
	});

	// 主题编辑相关
	const showTopicDialog = ref(false);
	const editingTopicIndex = ref<number>();
	const editingTopicData = ref<Partial<Topic>>();

	// 添加主题
	const addTopic = () => {
		editingTopicIndex.value = undefined;
		editingTopicData.value = undefined;
		showTopicDialog.value = true;
	};

	// 编辑主题
	const editTopic = (index: number) => {
		editingTopicIndex.value = index;
		editingTopicData.value = { ...formData.value.topics[index] };
		showTopicDialog.value = true;
	};

	// 删除主题
	const removeTopic = (index: number) => {
		formData.value.topics.splice(index, 1);
	};
	
	//处理主题
	const processTopic=(index: number,row:any)=>{
		dataProcessDrawerRef.value.openDialog(index,row);
	}

	// 处理主题确认
	const handleTopicConfirm = (topic: Topic, index?: number) => {
		if (index !== undefined) {
			formData.value.topics[index] = topic;
		} else {
			formData.value.topics.push(topic);
		}
	};

	// 发布主题编辑相关
	const showPublishDialog = ref(false);
	const editingPublishIndex = ref<number>();
	const editingPublishData = ref<Partial<Topic>>();

	// 添加发布主题
	const addPublish = () => {
		editingPublishIndex.value = undefined;
		editingPublishData.value = undefined;
		showPublishDialog.value = true;
	};

	// 编辑发布主题
	const editPublish = (index: number) => {
		editingPublishIndex.value = index;
		editingPublishData.value = { ...formData.value.publishTopics[index] };
		showPublishDialog.value = true;
	};

	// 删除发布主题
	const removePublish = (index: number) => {
		formData.value.publishTopics.splice(index, 1);
	};

	// 处理发布主题确认
	const handlePublishConfirm = (topic: Topic, index?: number) => {
		if (index !== undefined) {
			formData.value.publishTopics[index] = topic;
		} else {
			formData.value.publishTopics.push(topic);
		}
	};

	async function openDialog(row?: any, type?: string) {
		resetForm();
		
		dialog.value = {
			visible: true,
			title: type === 'add' ? '新增MQTT数据源' : '编辑MQTT数据源'
		};

		if (type === 'add') {
			formData.value = {
				prefix: '',
				host: '',
				username: '',
				password: '',
				timeout: DEFAULT_TIMEOUT,
				keepalive: 60,
				type: '0',
				topics: [],
				publishTopics: [],
				enabled:'0',
				defaultRunning:'0',
				use:'0'
			};
			return;
		}

		try {
			// 基础数据，显式声明类型
			const baseData: FormData = {
				id: row.id,
				name: row.name,
				prefix: row.prefix || '',
				host: row.host || '',
				username: row.username || '',
				password: row.password || '',
				timeout: row.timeout || DEFAULT_TIMEOUT,
				keepalive: row.keepalive || 60,
				type: row.type || '0',
				topics: [],
				publishTopics: [],
				enabled:row.enabled ||'0' ,
				defaultRunning:row.defaultRunning ||'0',
				use: row.use || '0'
			};

			// 解析数组类型的字段
			try {
				baseData.topics = row.topics ? JSON.parse(row.topics) : [];
			} catch (e) {
				console.warn('解析 topics 失败:', e);
				baseData.topics = [];
			}

			try {
				baseData.publishTopics = row.publishTopics ? JSON.parse(row.publishTopics) : [];
			} catch (e) {
				console.warn('解析 publishTopics 失败:', e);
				baseData.publishTopics = [];
			}

			// 解析配置信息
			if (row.config) {
				try {
					const config = JSON.parse(row.config);
					// 只更新存在的字段
					if (config.timeout) baseData.timeout = config.timeout;
					if (config.keepalive) baseData.keepalive = config.keepalive;
					if (config.type) baseData.type = config.type;
					
					// 解析数组类型的配置
					if (config.topics) {
						try {
							baseData.topics = typeof config.topics === 'string' 
								? JSON.parse(config.topics) 
								: config.topics;
						} catch (e) {
							console.warn('解析配置中的 topics 失败:', e);
						}
					}
					
					if (config.publishTopics) {
						try {
							baseData.publishTopics = typeof config.publishTopics === 'string' 
								? JSON.parse(config.publishTopics) 
								: config.publishTopics;
						} catch (e) {
							console.warn('解析配置中的 publishTopics 失败:', e);
						}
					}
				} catch (e) {
					console.warn('解析配置信息失败:', e);
				}
			}
			formData.value = baseData;
		} catch (e) {
			console.error('加载数据失败:', e);
			ElMessage.error('加载数据失败');
			closeDialog();
		}
	}
	
	const submitForm = () => {
		formRef.value.validate((isValid: boolean) => {
			if (isValid) {
				loading.value = true;
				
				// 构建保存数据
				const saveData = {
					id: formData.value.id,
					name: formData.value.name,
					prefix: formData.value.prefix,
					host: formData.value.host,
					username: formData.value.username,
					password: formData.value.password,
					timeout: formData.value.timeout,
					keepalive: formData.value.keepalive,
					type: formData.value.type,
					enabled:formData.value.enabled,
					defaultRunning:formData.value.defaultRunning,
					use: formData.value.use,
					topics: JSON.stringify(formData.value.topics),
					publishTopics: JSON.stringify(formData.value.publishTopics)
				};

				// 调用保存接口
				MqttAPI.save(saveData)
					.then(() => {
						ElMessage.success("保存成功");
						closeDialog();
					})
					.catch((error) => {
						console.error('保存失败:', error);
						ElMessage.error(error.message || "保存失败");
					})
					.finally(() => {
						loading.value = false;
					});
			} else {
				ElMessage.warning("请填写必填项");
			}
		});
	};
	
	const emits = defineEmits(['closeDialog'])
	const closeDialog=()=>{
		dialog.value.visible=false;
		dialog.value.title="";
		emits('closeDialog',formData)
		resetForm();
	}
	
	/**
	 * 重置表单
	 */
	function resetForm() {
		// 重置表单验证
		formRef.value?.resetFields();
		formRef.value?.clearValidate();

		// 重置表单数据
		formData.value = {
			// 基础信息
			id: undefined,
			name: undefined,
			prefix: '',
			host: '',
			username: '',
			password: '',
			timeout: DEFAULT_TIMEOUT,
			keepalive: 60,
			type: '0',
			topics: [],
			publishTopics: [],
			enabled:'0',
			defaultRunning:'1',
			use:'0'
		};
	}	
	
	// 监听客户端类型变化
	watch(() => formData.value.type, (newType) => {
		// 如果切换到生产者模式，清空订阅主题
		if (newType === '1') {
			formData.value.topics = [];
		}
		// 如果切换到消费者模式，清空发布主题
		if (newType === '0') {
			formData.value.publishTopics = [];
		}
	});

	defineExpose({
	  openDialog,closeDialog
	});
</script>

<style scoped>
	.title-form_primary {
		font-style: normal;
		font-weight: 500;
		font-size: 14px;
		color: #1f2329;
		position: relative;
		padding-left: 5px;
	}
	
	.title-form_primary:before {
		content: "";
		width: 2px;
		height: 14px;
		background: var(--el-color-primary);
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
		left: 0;
	}
	
	.row-content {
		display: flex;
		flex-direction: row;
		align-items: flex-start;
		margin-bottom: 10px;
	}

	.el-form-item {
		width: 100%;
	}

	.el-form-item__content {
		width: 100%;
	}

	.topic-item {
		border: 1px solid var(--el-border-color-light);
		border-radius: 4px;
		padding: 20px;
		margin-bottom: 20px;
	}

	.topic-options {
		display: flex;
		gap: 20px;
		margin: 10px 0;
	}

	.topic-actions {
		display: flex;
		justify-content: flex-end;
		margin-top: 10px;
	}

	:deep(.el-form-item) {
		margin-bottom: 18px;
	}

	:deep(.el-radio-group) {
		width: 100%;
	}

	:deep(.el-textarea) {
		width: 100%;
	}
</style>